<?php

namespace common\logics;

use Yii;
use common\helpers\ArrayHelper;
use common\helpers\StringHelper;
use common\helpers\Url;

/**
 * 商城栏目分类
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class ShopCategoryLogic extends \common\models\shop\ShopCategory {

    /**
     * 将数组转换成树形结构
     */
    public static function getCategoryTree() {
        $data = static::find()->active()->andWhere([
            'status' => self::STATUS_ACTIVE,
            'parent_id' => 0,
        ])->with(['channel', 'children', 'products'])
        ->orderBy([
            'listorder' => SORT_ASC,
        ])->all();
        if (empty($data)) {
            return $data;
        }
        return self::formatTree($data);
    }

    /**
     * 将数组转换成树形结构
     */
    public static function categoryLayer($id) {
        $model = static::findOne($id);
        if (!$model) {
            return null;
        }
        if ($model->parent_id) {
            $model = static::findOne($model->parent_id);
        }
        if (!$model) {
            return null;
        }

        $items = [];
        foreach ($model->children as $children) {
            $items[] = [
                'id' => $children->id,
                'name' => $children->name,
                'link' => Url::h5('shop/category/' . $children->id),
            ];
        }

        return [
            'title' => $model->name,
            'items' => $items,
        ];
    }

    protected static function formatTree($tree, $pkey = 0) {
        $return = [];
        foreach ($tree as $branch) {
            if (empty($branch->children)) {
                continue;
            }
            $temp = $branch->toArray([], ['channel']);
            $channel = ArrayHelper::remove($temp, 'channel');
            //二级分类
            $children = [];
            foreach ($branch->children as $leaf) {
                $_temp = $leaf->toArray();
                $spread = ArrayHelper::remove($_temp, 'spread', ['image' => '', 'link' => '']);
                $children[] = ArrayHelper::merge($_temp, $spread, $leaf->formatCateNode);
            }
            $temp['children'][] = [
                'id' => $branch->id,
                'name' => $branch->name,
                'level' => 2,
                'channel' => $channel,
                'children' => $children
            ];
            $return[] = $temp;
        }
        return $return;
    }

    /**
     * 将数组转换成树形结构
     */
    protected static function formatCategoryTree($tree, $pkey = 0, $keyname = 'id', $pkname = 'parent_id', $childname = 'children') {

        $return = [];
        foreach ($tree as $key => $leaf) {
            $id = ArrayHelper::getValue($leaf, $keyname);
            $pid = ArrayHelper::getValue($leaf, $pkname);
            if ($pid != $pkey) {
                continue;
            }
            ArrayHelper::remove($tree, $key);
            foreach ($tree as $temp) {
                if ($temp[$pkname] == $id) {
                    $child = self::formatCategoryTree($tree, $id, $keyname, $pkname, $childname);
                    ArrayHelper::setValue($leaf, $childname, $child);
                    break;
                }
            }
            $temp = self::formatCategoryItem($leaf);
            if ($temp) {
                $return[] = $temp;
            }
        }
        return $return;
    }

    protected static function formatCategoryItem($leaf) {
        $level = $leaf['level'];
        ArrayHelper::remove($leaf, 'parent_id');
        ArrayHelper::remove($leaf, 'channel_id');
        $link = ArrayHelper::remove($leaf, 'link');
        if ($level > 1) {
            ArrayHelper::remove($leaf, 'spread');
        }
        if ($level == 2) {
            $childname = 'children';
            $children = ArrayHelper::getValue($leaf, $childname, []);
            if (empty($children)) {
                $children = [
                    [
                        "id" => "51",
                        "name" => "精致圆领",
                        "level" => "3",
                        "image" => '',
                        "link" => '',
                        "type" => 'goods',
                    ],
                ];
                ArrayHelper::setValue($leaf, $childname, $children);
            }
            if (!empty($leaf['channel'])) {
                $channel = $leaf['channel'];
                $leaf['channel'] = [
                    'name' => '进入' . $channel['name'] . '频道 >',
                    'link' => $channel['link'],
                ];
            }
        } else {
            ArrayHelper::remove($leaf, 'channel');
        }
        if ($level == 3) {
            $type = 'category';
            if ($link) {
                $type = 'link';
            } else {
                $link = '';
            }
            ArrayHelper::setValue($leaf, 'link', $link);
            ArrayHelper::setValue($leaf, 'type', $type);
        } else {
            ArrayHelper::remove($leaf, 'image');
        }
        return $leaf;
    }

    protected static function updateLevel($max = 3) {
        $parentids = 0;
        for ($i = 0; $i < $max; $i++) {
            $level = $i + 1;
            static::updateAll(['level' => $level], ['parent_id' => $parentids]);
            $parentids = static::find()->where(['level' => $level])->column();
        }
    }

    public function fields() {
        return [
            'id',
            'name',
//            'level',
            'spread' => function () {
                return [
                    'image' => Url::attach($this->image),
                    'link' => $this->link,
                ];
            },
        ];
    }

}
